package com.trainoo.service.impl;

import com.trainoo.service.IFileUploadService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;

/**
 * <p> description here </p>
 *
 * @author tao.zhou
 * @version 1.0
 * @date 2020/6/9 19:37
 */
@Slf4j
@RestController
public class FileUploadServiceImpl implements IFileUploadService {

    @Override
    public void uploadOne(MultipartFile multipartFile, String  value) {
        String originalFilename = multipartFile.getOriginalFilename();
        log.debug("filename={}", originalFilename);

        try {

            /// 临时注释
            /*File file = File.createTempFile("tmp", "txt");
            multipartFile.transferTo(file);
            FileChannel fc = new FileInputStream(file).getChannel();
            ByteBuffer byteBuf = ByteBuffer.allocate(1024*1000);
            while (fc.read(byteBuf) != -1) {
                byteBuf.flip();

                Charset.forName("utf-8").decode(byteBuf).toString();
                System.out.println(byteBuf);
                byteBuf.clear();
            }*/

            File file = File.createTempFile("tmp", "txt");
            multipartFile.transferTo(file);
            try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
                String line = null;
                while ((line = reader.readLine()) != null) {
                    System.out.println(line);
                }
            } catch (IOException x) {
                System.err.format("IOException: %s%n", x);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
